package kr.couponplay.android.support;

import java.util.ArrayList;
import java.util.List;

import kr.couponplay.android.AppContext;
import kr.couponplay.android.domain.deal.Provider;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ProviderUtils {
	
	public static void setting(String jsonString) {
		try {
			JSONArray jSONArray = new JSONArray(jsonString);
			AppContext.setProviders(parse(jSONArray));
		} catch (Exception e) {
			throw new IllegalArgumentException(e.getMessage(), e);
		}
	}
	
	private static List<Provider> parse(JSONArray jSONArray) throws JSONException {
		List<Provider> providers = new ArrayList<Provider>();
		for (int i = 0; i < jSONArray.length(); i++) {
			Provider provider = new Provider();
			provider.setNo(jSONArray.getJSONObject(i).getInt("no"));
			provider.setCode(jSONArray.getJSONObject(i).getString("code"));
			provider.setName(jSONArray.getJSONObject(i).getString("name"));
			provider.setHomepage(jSONArray.getJSONObject(i).getString("homepage"));
			provider.setTelephone(jSONArray.getJSONObject(i).getString("telephone"));
			provider.setJoinUrl(getStringValue(jSONArray.getJSONObject(i), "joinUrl"));
			provider.setRegisteTime(jSONArray.getJSONObject(i).getLong("registeTime"));
			providers.add(provider);
		}
		return providers;
	}
	
	private static String getStringValue(JSONObject json, String name) throws JSONException {
		if(json.isNull(name)) {
		    return null;
		}
		return json.getString(name);
	}
}
